#include "Protocol.hpp"
#include "TcpServer.hpp"
#include "Socket.hpp"
#include "Calculate.hpp"
#include <iostream>
#include <memory>
#include <unistd.h>


// 网络负责IO发送
// HandlerRequest字节流数据解析和调用业务处理方法的
// 处理报文的方法
std::string HandlerRequest(std::string &inbufferstream, bool *error_code)
{
    sleep(1);
    Calculate calculate;    // 实例化计算器   
    std::string reqstr;
    // 1. 构造请求对象
    std::unique_ptr<Factory> factory(new Factory());
    std::shared_ptr<Request> req = factory->BuildRequest();

    // 2. 解包
    std::string sendstr;
    while(Decode(inbufferstream, &reqstr))  // 循环处理，可能存在一段字节流中有多个报文的情况
    {
        // 3. 拿到完整请求报文，反序列化
        if(!req->Deserialize(reqstr))
        {
            // 解析不成功，设置状态码为false，返回空串
            lg.LogMessage(Debug, "Deserialize failed...\n");
            *error_code = false;
            return std::string();
        }
        // 解析成功
        lg.LogMessage(Debug, "Deserialize success...\n");
        // 4. 业务处理，拿到响应
        std::shared_ptr<Response> response = calculate.Cal(req);
        // 5. 序列化response
        std::string responsestr;
        response->Serialize(&responsestr);
        // 6. 封装报头
        std::string package = Encode(responsestr);
        // 7. 构造发送字符串，设置状态码为true
        *error_code = true;
        sendstr += package;
    }

    return sendstr;
}

// ./server port
int main(int argc, char *argv[])
{
    if(argc != 2)
    {
        std::cout << "Usage: " << argv[0] << "port" << std::endl;
        return 0;
    }
    uint16_t localport = std::stoi(argv[1]);

    std::unique_ptr<TcpServer> tsvr(new TcpServer(localport, HandlerRequest));
    tsvr->Loop();   // 服务器启动

    return 0;
}